<template>
  <el-dialog>
    <el-upload
      ref="uploadRef"
      action="#"
      :limit="1"
      :on-exceed="handleExceed"
      :auto-upload="false"
      :before-upload="beforeUpload"
      :on-change="handleChange"
    >
      <el-button type="success">选择文件</el-button>
      <template #tip>
        <div class="el-upload__tip" style="color: red">
          仅限上传1个文件, 选择新的文件将会覆盖原有的文件!
        </div>
      </template>
    </el-upload>
    <slot name="uploadDialogSlot"></slot>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          style="float: left"
          type="primary"
          @click="
            changeUploadDialogVisible();
            batchUpload(dataList);
          "
          >确认上传
        </el-button>
        <el-button @click="changeUploadDialogVisible">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { inject, ref, defineEmits } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import { read, utils } from "xlsx";

const emit = defineEmits<{
  (
    e: "submit-json-format",
    data: Record<string, unknown>[][],
    callback: (value: Record<string, unknown>[]) => void
  ): void;
}>();

// 上传
const changeUploadDialogVisible = inject("changeUploadDialogVisible");

const uploadRef = ref();

const handleExceed = (files: File[]) => {
  ElMessage.warning("当前选择文件覆盖了之前选择的文件!");
  uploadRef.value.clearFiles();
  uploadRef.value.handleStart(files[0]);
};

const beforeUpload = (file: never) => {
  console.log("test");
  console.log(file);
};

const dataList = ref();

const handleChange = (file: Record<string, unknown>) => {
  ElLoading.service({ text: "表格读取中..." });
  if (file) {
    try {
      let reader = new FileReader();
      reader.onload = (ev: ProgressEvent<FileReader>) => {
        const excelData = ev.target?.result;
        const wb = read(excelData, { type: "binary" });
        const data: Record<string, unknown>[][] = [];
        wb.SheetNames.forEach((sheetName: string, index: number) => {
          data[index] = utils.sheet_to_json(wb.Sheets[sheetName]);
        });
        emit("submit-json-format", data, (value: Record<string, unknown>[]) => {
          dataList.value = value;
        });
      };
      reader.readAsArrayBuffer(file.raw as Blob);
      ElMessage.success({ message: "读取成功!" });
    } catch (e) {
      console.log(e);
      ElMessage.error({ message: "读取失败!" });
    }
  }
  ElLoading.service().close();
};

const batchUpload = inject("batchSubmit");
</script>

<style scoped></style>
